<?php
namespace App\Service\Admin\Qudao;

use App\Service\Admin\BaseService as Service;
use App\Service\Admin\UserService;

class CardService extends Service
{
    //礼品卡

    //选项
    public function getOption()
    {
        $arys['cate'][] = ['id' => 0, 'title' => '所有'];
        $res = $this->dbConn($this->dbQdCcate)->where('del', 0)->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $arys['cate'][] = [
                    'id' => $v['id'],
                    'title' => $v['cate_name'],
                ];
            }
        }
        return $arys;
    }

    /**
     * 列表
     */
    public function getList()
    {
        $this->imgDel(); //清理图片
        $db = $this->dbConn($this->dbQdCard)->where('del', 0);
        $total = $db->count();
        $res = $db->orderBy('id', 'desc')->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $cateOne = (array) $this->dbConn($this->dbQdCcate)
                ->where('id', $v['cate_id'])
                ->first();
            if (file_exists($v['img_url'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            $imgList = [];
            $imgOnes = $this->dbConn($this->dbQdCimg)->where('card_id', $v['id'])->get();
            if (count($imgOnes)){
                foreach ($imgOnes as $imgOne) {
                    $imgOne = (array) $imgOne;
                    $imgList = file_exists($imgOne['link']) ? env('DOMAIN').'/'.$imgOne['link'] : $imgOne['link'];
                }
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'cate_id' => $v['cate_id'],
                'cate_name' => empty($cateOne) ? '-' : $cateOne['cate_name'],
                'imgPrefix' => $imgPrefix,
                'imgLink' => $v['img_url'],
                'imgList' => $imgList,
                'uptime' => $v['addtime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 详情
     */
    public function getOne($id)
    {
        $res = (array) $this->dbConn($this->dbQdCard)->where('id', $id)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $cateOne = (array) $this->dbConn($this->dbQdCcate)
            ->where('id', $id)
            ->first();
        if (file_exists($res['img_url'])) {
            $imgPrefix = env('DOMAIN') . '/';
        } else {
            $imgPrefix = env('FC_DOMAIN') . '/';
        }
        $imgList = [];
        $imgOnes = $this->dbConn($this->dbQdCimg)->where('card_id', $id)->get();
        if (count($imgOnes)){
            foreach ($imgOnes as $imgOne) {
                $imgOne = (array) $imgOne;
                $imgList[] = file_exists($imgOne['link']) ? '/'.$imgOne['link'] : $imgOne['link'];
            }
        }
        $arys = [
            'id' => $res['id'],
            'title' => $res['title'],
            'cate_id' => $res['cate_id'],
            'cate_name' => empty($cateOne) ? '-' : $cateOne['cate_name'],
            'imgPrefix' => $imgPrefix,
            'imgLink' => $res['img_url'],
            'imgList' => $imgList,
            'uptime' => $res['uptime'],
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 添加
     * @param array $pas
     */
    public function add($pas)
    {
        $res = (array) $this->dbConn($this->dbQdCard)
            ->where('del', 0)
            ->where('title', $pas['title'])
            ->first();
        if (!empty($res)) {
            return $this->toback(-2, '存在同名记录');
        }
        $pas['uptime'] = $pas['addtime'] = toDate();
        $lastid = $this->dbConn($this->dbQdCard)->insertGetId($pas);
        if (!$lastid) {
            return $this->toback(-1, '添加失败');
        }
        $this->imgModify($lastid); //刷新图片
        return $this->toback();
    }

    /**
     * 修改
     * @param int $id
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $res = (array) $this->dbConn($this->dbQdCard)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '记录不存在');
        }
        $pas['uptime'] = toDate();
        $lastid = $this->dbConn($this->dbQdCard)->where('id', $id)->update($pas);
        if (!$lastid) {
            return $this->toback(-1, '修改失败');
        }
        $this->imgModify($id); //刷新图片
        return $this->toback();
    }

    /**
     * 删除
     * @param int $id
     */
    public function setDel($id)
    {
        $res = (array) $this->dbConn($this->dbQdCard)
            ->where('del', 0)
            ->where('id', $id)
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '记录不存在');
        }
        $up = $this->dbConn($this->dbQdCard)->where('id', $id)
            ->update(['del' => 1, 'deltime' => toDate()]);
        if (!$up) {
            return $this->toback(-1, '删除失败');
        }
        return $this->toback();
    }

    /**
     * 商品列表
     */
    public function goodsList()
    {
        $db = $this->dbConn($this->dbQdCgoods)->where('del', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $cardOne = (array) $this->dbConn($this->dbQdCard)
                ->where('id', $v['card_id'])
                ->first();
            if (file_exists($v['img_url'])) {
                $imgPrefix = env('DOMAIN') . '/';
            } else {
                $imgPrefix = env('FC_DOMAIN') . '/';
            }
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'card_id' => $v['card_id'],
                'card_name' => empty($cardOne) ? '-' : $cardOne['title'],
                'price' => $v['price'] / 100,
                'code' => $v['code'],
                'num' => $v['stock'],
                'imgPrefix' => $imgPrefix,
                'imgLink' => $v['img_url'],
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 用户列表
     * @param array $pages【start，limit】
     */
    public function userList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbQdCuser)
//            ->where('del', 0)
//            ->where('from_id', '>', 0);
            ->where([
                ['del', '=', 0],
                ['from_id', '=', 0],
                ['is_transfer', '=', 1],
            ])
            ->orWhere([
                ['del', '=', 0],
                ['from_id', '>', 0],
            ]);
        $total = $db->count();
        $res = $db->orderBy('id', 'dsc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['uid'])
                ->first();
            $cardOne = (array) $this->dbConn($this->dbQdCard)
                ->where('id', $v['card_id'])
                ->first();
            $gOne = (array) $this->dbConn($this->dbQdCgoods)
                ->where('id', $v['card_goods_id'])
                ->first();
            //转赠原ID
            $new_id = 0;
            if ($v['is_transfer']) {
                $lastOne = (array) $this->dbConn($this->dbQdCuser)
                    ->where('from_id', $v['id'])
                    ->first();
                $new_id = empty($lastOne) ? 0 : $lastOne['id'];
            }
            $arys[] = [
                'id' => $v['id'],
                'uname' => empty($uOne) ? '-' : $uOne['nickname'],
                'card_name' => empty($cardOne) ? '-' : $cardOne['title'],
                'gname' => empty($gOne) ? '-' : $gOne['title'],
                'price' => $v['price'] / 100,
                'num' => $v['num'],
                'code' => $v['code'],
                'is_used' => $v['is_used'],
                'is_transfer' => $v['is_transfer'],
                'new_id' => $new_id,
                'addtime' => $v['addtime'] ? $v['addtime'] : '-',
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 订单列表
     * @param array $pages【start，limit】
     */
    public function orderList($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbQdCuser)
            ->where('del', 0)
            ->where('from_id', 0);
        $total = $db->count();
        $res = $db->orderBy('id', 'dsc')
            ->skip($start)->take($pages['limit'])
            ->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $uOne = (array) $this->dbConn($this->dbUser)
                ->where('id', $v['uid'])
                ->first();
            $cardOne = (array) $this->dbConn($this->dbQdCard)
                ->where('id', $v['card_id'])
                ->first();
            $arys[] = [
                'id' => $v['id'],
                'uname' => empty($uOne) ? '-' : $uOne['nickname'],
                'card_name' => empty($cardOne) ? '-' : $cardOne['title'],
                'price' => toNumber($v['price']),
                'addtime' => $v['addtime'] ? $v['addtime'] : '-',
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 分类列表
     */
    public function cateList()
    {
        $db = $this->dbConn($this->dbQdCcate)->where('del', 0);
        $total = $db->count();
        $res = $db->get();
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $arys[] = [
                'id' => $v['id'],
                'cate_name' => $v['cate_name'],
                'uptime' => $v['uptime'],
            ];
        }
        return $this->toback(0, '', $arys, $total);
    }

    /**
     * 分类更新
     */
    public function cateModify($id, $cname)
    {
        if ($id) {
            $res = $this->dbConn($this->dbQdCcate)->where('id', $id)->first();
            if (empty($res)) {
                return $this->toback(-2, '没有记录');
            }
            $up = $this->dbConn($this->dbQdCcate)->where('id', $id)->update([
                'cate_name' => $cname, 'uptime' => toDate(),
            ]);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        } else {
            $res = $this->dbConn($this->dbQdCcate)->where('cate_name', $cname)->first();
            if (!empty($res)) {
                return $this->toback(-2, '存在同名分类');
            }
            $up = $this->dbConn($this->dbQdCcate)->insertGetId([
                'cate_name' => $cname, 'addtime' => toDate(), 'uptime' => toDate(),
            ]);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        }
        return $this->toback();
    }

    /**
     * 分类更新
     */
    public function cateDel($id)
    {
        $res = $this->dbConn($this->dbQdCcate)->where('id', $id)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $this->dbConn($this->dbQdCcate)->where('id', $id)->update(['del' => 1]);
        return $this->toback();
    }

    //选项
    public function goodsOption()
    {
        $arys = ['card' => []];
        $res = $this->dbConn($this->dbQdCard)->where('del', 0)->get();
        if (count($res)) {
            foreach ($res as $v) {
                $v = (array) $v;
                $arys['card'][] = [
                    'id' => $v['id'],
                    'title' => $v['title'],
                ];
            }
        }
        return $arys;
    }

    /**
     * 分类更新
     * @param int $id
     * @param string $serial
     * @param array $pas
     */
    public function goodsModify($id, $pas)
    {
        $cardOne = (array) $this->dbConn($this->dbQdCard)->where('id', $pas['card_id'])->first();
        if (empty($cardOne)) {
            return $this->toback(-2, '没有记录');
        }
        $code = toCardCode();
        if ($id) {
            $res = $this->dbConn($this->dbQdCgoods)->where('id', $id)->first();
            if (empty($res)) {
                return $this->toback(-2, '没有记录');
            }
            $up = $this->dbConn($this->dbQdCgoods)->where('id', $id)->update([
                'title' => $pas['title'], 'price' => $pas['price'] * 100,
                'stock' => $pas['num'], 'card_id' => $pas['card_id'],
                'uptime' => toDate(),
            ]);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        } else {
            $res = $this->dbConn($this->dbQdCgoods)->where('title', $pas['title'])->first();
            if (!empty($res)) {
                return $this->toback(-2, '存在同名卡');
            }
            $up = $this->dbConn($this->dbQdCgoods)->insertGetId([
                'title' => $pas['title'], 'price' => $pas['price'] * 100,
                'stock' => $pas['num'], 'card_id' => $pas['card_id'],
                'img_url' => $cardOne['img_url'], 'code' => $code,
                'addtime' => toDate(), 'uptime' => toDate(),
            ]);
            if (!$up) {
                return $this->toback(-1, 'error');
            }
        }
        return $this->toback();
    }

    /**
     * 删除
     * @param int $id
     * @param string $serial
     * @param array $pas
     */
    public function goodsDel($id)
    {
        $res = $this->dbConn($this->dbQdCgoods)->where('id', $id)->first();
        if (empty($res)) {
            return $this->toback(-2, '没有记录');
        }
        $up = $this->dbConn($this->dbQdCgoods)->where('id', $id)->update([
            'del' => 1, 'deltime' => toDate(),
        ]);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 添加图片
     * @param int $id
     * @param string $img 图片
     * @param int $w 宽度
     * @param int $h 高度
     */
    public function addImg($id, $img, $w, $h)
    {
        //素材库
        $cData = [
            'card_id' => $id, 'link' => $img,
            'width' => $w, 'height' => $h,
            'addtime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbQdCimg)->insertGetId($cData);
        if (!$lastid) {
            return $this->toback(-1, '图片失败');
        }
        //图库
        $imgData = [
            'link' => $img,
            'width' => $w,
            'height' => $h,
            'addtime' => toDate(),
        ];
        $lastid = $this->dbConn($this->dbImg)->insertGetId($imgData);
        if (!$lastid) {
            return $this->toback(-1, '图库失败');
        }
        return $this->toback();
    }

    //获取已上传的图片集合
    public function imgList($cardId)
    {
        return $this->dbConn($this->dbCardImg)
            ->where('del', 0)
            ->where('card_id', $cardId)
            ->get();
    }

    //获取已上传的图片集合
    public function imgModify($cardId)
    {
        return $this->dbConn($this->dbCardImg)
            ->where('del', 0)
            ->where('card_id', 0)
            ->update(['card_id' => $cardId]);
    }

    //上传过时的图片
    public function imgDel()
    {
        return $this->dbConn($this->dbCardImg)
            ->where('del', 0)
            ->where('card_id', 0)
            ->update(['del' => 1, 'deltime' => toDate()]);
    }
}